package controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

/**
 * @author 石小俊
 */
@Controller
@RequestMapping("/hello")
public class HelloController {

    @RequestMapping("/sayHello")
    public ModelAndView sayHello() {
        ModelAndView mav = new ModelAndView();
        // 相当于request.setAttribute(key,value)
        mav.addObject("msg", "<span style='color:green;'>Hello World</span>");
        // 返回视图名
        // 最终访问的页面为:前缀+视图名+后缀
        mav.setViewName("hello");
        return mav;
    }

    @RequestMapping("/showLogin")
    public String showLogin() {
        // 直接写字符串,表示视图名
        return "login";
    }

    @RequestMapping("/showLogin2")
    public ModelAndView showLogin2() {
        ModelAndView mav = new ModelAndView();
        // 返回视图名
        // 最终访问的页面为:前缀+视图名+后缀
        mav.setViewName("login");
        return mav;
    }

    @RequestMapping("/showLogin3")
    public String showLogin3() {
        // 转发到/showLogin
        return "forward:/showLogin";
    }

    @RequestMapping("/showLogin4")
    public String showLogin4() {
        // 重定向到/showLogin
        return "redirect:/showLogin";
    }

    // 参数中没有响应对象,默认以当前的请求名作为视图名返回
    // 请求名:/hello/f1
    // 访问的页面:/WEB-INF/pages/hello/f1.jsp
    @RequestMapping("/f1")
    public void f1() {
        System.out.println("HelloController.f1");
    }

    // 参数中存在响应对象,则响应结果交给响应对象的参数来处理
    @RequestMapping("/f2")
    public void f2(HttpServletResponse response) {
        System.out.println("HelloController.f2");
    }

    @RequestMapping("/f3")
    public void f3(PrintWriter out) {
        out.println("<h1>Hello World</h1>");
    }

    @ResponseBody
    @RequestMapping("/f4")
    public String f4() {
        return "<h1>Hello World</h1>";
    }


    @RequestMapping("/login")
    public void login(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        request.setCharacterEncoding("utf-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println("username:" + username + ",password:" + password);
    }

    @RequestMapping("/login2")
    public void login2(@RequestParam("username") String username, @RequestParam String password) {
        System.out.println("username:" + username + ",password:" + password);
    }
}
